package com.anime.activity;

import android.os.Bundle;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.anime.adapter.LRYAnimeSelectionAdapter;
import com.anime.adapter.YHAnimeSelectionAdapter;
import com.anime.model.ViewModelSwitch;
import com.animes.R;
import com.animes.databinding.AnimePlayActivityBinding;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tencent.liteav.demo.superplayer.SuperPlayerGlobalConfig;
import com.tencent.liteav.demo.superplayer.SuperPlayerModel;
import com.tencent.liteav.demo.superplayer.SuperPlayerView;


import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import anime.play.room.AnimePlayHistoryModel;
import anime.play.room.AnimePlayHistoryViewModel;
import anime.room.HistoryModel;
import anime.room.HistoryViewModel;
import base.QActivity;
import base.QLoading;
import constant.AppConstants;
import http.Api;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import model.AnimeLRYChapterModel;
import model.AnimeYHChapterModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class AnimePlayActivity extends QActivity {

    private String lryId;
    private AnimePlayActivityBinding binding;
    private LRYAnimeSelectionAdapter lryAnimeSelectionAdapter;
    private boolean isOne = true;

    // String url = "https://vip.lz-cdn9.com/20230521/17542_f9e8d7f1/index.m3u8";
    private SuperPlayerModel model;
    private String url;
    private Disposable disposable;
    private String title;
    private int type;
    private YHAnimeSelectionAdapter yhAnimeSelectionAdapter;
    private Integer yhid;
    private Disposable stopDisposable;
    private Disposable yhdisposable;
    boolean isOnePlay = true;
    private QLoading dialog;
    private AnimePlayHistoryViewModel viewModel;
    private String pic;
    private String titleName;
    private String historyurl;

    @Override
    public int getLayoutRes() {
        return R.layout.anime_play_activity;

    }

    @Override
    public void initView() {
        binding = DataBindingUtil.setContentView(this, getLayoutRes());
    }

    @Override
    public void initData() {

        Bundle bundle = getIntent().getExtras();
        lryId = bundle.getString("videoId");
        yhid = bundle.getInt("yhid");
        type = bundle.getInt("type", 0);
        historyurl = bundle.getString("historyurl");


        pic = bundle.getString("pic");
        titleName = bundle.getString("titleName");

        binding.tvDescs.setSelected(true);

        viewModel = new ViewModelProvider(this).get(AnimePlayHistoryViewModel.class);


        LinearLayoutManager lrylayoutManager = new LinearLayoutManager(this);
        lrylayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        binding.rvLryselection.setLayoutManager(lrylayoutManager);
        lryAnimeSelectionAdapter = new LRYAnimeSelectionAdapter(R.layout.anime_selection_item, null);
        binding.rvLryselection.setAdapter(lryAnimeSelectionAdapter);


        LinearLayoutManager yhlayoutManager = new LinearLayoutManager(this);
        yhlayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        binding.rvYhselection.setLayoutManager(yhlayoutManager);
        yhAnimeSelectionAdapter = new YHAnimeSelectionAdapter(R.layout.anime_selection_item, null);
        binding.rvYhselection.setAdapter(yhAnimeSelectionAdapter);

        SuperPlayerGlobalConfig.getInstance().enablePIP = false;
        model = new SuperPlayerModel();


    }


    public void play(String url) {


        LogUtils.d("播放地址：" + url);

        int animePlayHistory = SPStaticUtils.getInt("AnimePlayHistory", 0);
        int newId = animePlayHistory + 1;
        LogUtils.d("保存的Id" + newId);
        SPStaticUtils.put("AnimePlayHistory", newId);

        long progress = SPStaticUtils.getLong(url);

        if (type == 1) {
            viewModel.addHistoryDao(new AnimePlayHistoryModel(newId, progress, title, titleName, url, pic, type, lryId));
        } else if (type == 2) {
            viewModel.addHistoryDao(new AnimePlayHistoryModel(newId, progress, title, titleName, url, pic, type, yhid));
        }

        viewModel.getAllSLive().getValue();


        binding.tvSp.setText("视频：" + title);
        model.appId = 1; // 配置 AppId
        model.url = url;   // 配置您的播放视频 url
        binding.superVodPlayerView.playWithModelNeedLicence(model);

        binding.superVodPlayerView.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (url != null) {
                    long progress = SPStaticUtils.getLong(url);
                    LogUtils.d("当前播放器进度B--->：" + progress);

                    binding.superVodPlayerView.setSeek(progress);
                }


            }
        }, 150);//300 /150 3可以 快了慢了会有问题目前


    }


    public void setTime() {
        stopDisposable(disposable);
        disposable = Flowable.timer(60 * 1000, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (url != null) {
                            long progress = SPStaticUtils.getLong(url);
                            LogUtils.d("播放地址--->:" + url + "--->上次进度" + progress);
                            SPStaticUtils.put(url, binding.superVodPlayerView.getProgress());
                            setTime();
                        }


                    }
                });
    }


    /**
     * 关闭定时器
     *
     * @param disposable 定时器
     */
    private void stopDisposable(Disposable disposable) {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    @Override
    public void initListener() {

//        viewModel.getAllSLive().observe(this, new Observer<List<AnimePlayHistoryModel>>() {
//            @Override
//            public void onChanged(List<AnimePlayHistoryModel> animePlayHistoryModels) {
//                11
//            }
//        });


        binding.superVodPlayerView.setPlayerViewCallback(new SuperPlayerView.OnSuperPlayerViewCallback() {
            @Override
            public void onStartFullScreenPlay() {
                //开始全屏播放
                binding.clContext.setVisibility(View.GONE);
            }

            @Override
            public void onStopFullScreenPlay() {
                //结束全屏播放
                binding.clContext.setVisibility(View.VISIBLE);
            }

            @Override
            public void onClickFloatCloseBtn() {
                //点击悬浮窗模式下的x按钮
            }

            @Override
            public void onClickSmallReturnBtn() {
                //点击小播放模式的返回按钮
            }

            @Override
            public void onStartFloatWindowPlay() {
                //开始悬浮窗播放
            }

            @Override
            public void onPlaying() {
                //开始播放回调
            }

            @Override
            public void onPlayEnd() {
                //播放结束
            }

            @Override
            public void onError(int code) {
                LogUtils.d("播放错误" + code);
                ToastUtils.showLong("播放错误");
                //当播放失败的时候回调
            }

            @Override
            public void onShowCacheListClick() {
                //下载页面，点击了缓存列表按钮
            }
        });

        lryAnimeSelectionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AnimeLRYChapterModel.DataBean.ChapterListBean item = (AnimeLRYChapterModel.DataBean.ChapterListBean) adapter.getData().get(position);
                url = item.getLRYChapterPath();
                title = item.getTitle();
                setTime();
                play(url);
                lryAnimeSelectionAdapter.setIndex(position);
                lryAnimeSelectionAdapter.notifyDataSetChanged();
            }
        });


        yhAnimeSelectionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AnimeYHChapterModel.DataBean.PlayUrlBean item = (AnimeYHChapterModel.DataBean.PlayUrlBean) adapter.getData().get(position);
                url = item.getUrl();
                title = item.getTitle();
                setTime();
                play(url);
                yhAnimeSelectionAdapter.setIndex(position);
                yhAnimeSelectionAdapter.notifyDataSetChanged();
            }
        });


    }

    private List<AnimeLRYChapterModel.DataBean.ChapterListBean> listBeans = new ArrayList<>();

    @Override

    public void networkMessage() {
        dialog = new QLoading();
        dialog.showNow(getSupportFragmentManager(), "");

        if (type == 1) {
            binding.rvLryselection.setVisibility(View.VISIBLE);
            binding.rvYhselection.setVisibility(View.GONE);
            getLRYChapter();
        } else if (type == 2) {
            binding.rvLryselection.setVisibility(View.GONE);
            binding.rvYhselection.setVisibility(View.VISIBLE);
            getYHChapter();
        }

    }


    private HashMap<String, String> map = new HashMap<String, String>();

    private int networkIndex = 0;


    public void getYHChapter() {

        map.clear();
        map.put("id", String.valueOf(yhid));
        Call<AnimeYHChapterModel> call = Api.getInstance().service.getYHChapter(map);
        call.enqueue(new Callback<AnimeYHChapterModel>() {


            @Override
            public void onResponse(Call<AnimeYHChapterModel> call, Response<AnimeYHChapterModel> response) {
                LogUtils.d("网络请求数据" + call.toString(), response.body());
                if (response.body() != null && response.body().getData() != null && response.body().getData().getPlay_url() != null) {
                    String stringWithoutNbsp = response.body().getData().getContent().replaceAll("&nbsp;|\\s+", "");
                    binding.tvDescs.setText(stringWithoutNbsp);
                    yhAnimeSelectionAdapter.replaceData(response.body().getData().getPlay_url());
                    dialog.dismiss();
                    if (isOne) {
                        isOne = false;
                        setTime();
                    }
                    for (int i = yhAnimeSelectionAdapter.getData().size() - 1; i >= 0; i--) {
                        if (historyurl != null) {
                            isOnePlay = false;
                            if (StringUtils.equals(response.body().getData().getPlay_url().get(i).getUrl(), historyurl)) {
                                title = response.body().getData().getPlay_url().get(i).getTitle();
                                //这里是从历史记录过来的
                                isOnePlay = false;
                                yhAnimeSelectionAdapter.setIndex(i);
                                yhAnimeSelectionAdapter.notifyDataSetChanged();
                                binding.rvYhselection.scrollToPosition(i);
                                play(historyurl);


                                return;
                            }
                        }


                    }


                    for (int i = yhAnimeSelectionAdapter.getData().size() - 1; i >= 0; i--) {
                        title = yhAnimeSelectionAdapter.getData().get(i).getTitle();
                        url = yhAnimeSelectionAdapter.getData().get(i).getUrl();

                        String spTitle = SPStaticUtils.getString(url + title);


                        if (StringUtils.equals(spTitle, title)) {
                            isOnePlay = false;
                            LogUtils.d("解放军B" + title);
                            yhAnimeSelectionAdapter.setIndex(i);
                            yhAnimeSelectionAdapter.notifyDataSetChanged();
                            binding.rvYhselection.scrollToPosition(i);
                            play(url);

                            return;
                        }
                    }

                    if (isOnePlay) {
                        LogUtils.d("解放军C");
                        url = response.body().getData().getPlay_url().get(0).getUrl();
                        title = response.body().getData().getPlay_url().get(0).getTitle();
                        play(url);

                    }


                    binding.tvTitle.setText(response.body().getData().getName());
                } else {
                    if (networkIndex == 0) {
                        getYHChapter();
                        networkIndex++;
                    }
                    ToastUtils.showLong("正在再次搜索，内心等待！");


                }


            }

            @Override
            public void onFailure(Call<AnimeYHChapterModel> call, Throwable t) {
                LogUtils.d("网络请求失败:" + t.getMessage());
                ToastUtils.showLong("网络请求失败:" + t.getMessage());

            }
        });
    }


    public void getLRYChapter() {
        LogUtils.d("开发基地"+lryId);
        Call<AnimeLRYChapterModel> call = Api.getInstance().service.getLRYChapter(lryId);
        call.enqueue(new Callback<AnimeLRYChapterModel>() {


            @Override
            public void onResponse(Call<AnimeLRYChapterModel> call, Response<AnimeLRYChapterModel> response) {
                LogUtils.d("网络请求数据" + call.toString(), response.body());
                if (response.body() != null && response.body().getData() != null) {

                    String stringWithoutNbsp = response.body().getData().getDescs().replaceAll("&nbsp;|\\s+", "");
                    binding.tvDescs.setText(stringWithoutNbsp);
                    lryAnimeSelectionAdapter.replaceData(response.body().getData().getLRYChapterList());
                    dialog.dismiss();

                    if (isOne) {
                        isOne = false;
                        setTime();


                    }


                    for (int i = lryAnimeSelectionAdapter.getData().size() - 1; i >= 0; i--) {
                        title = lryAnimeSelectionAdapter.getData().get(i).getTitle();
                        url = lryAnimeSelectionAdapter.getData().get(i).getLRYChapterPath();
                        String spTitle = SPStaticUtils.getString(url + title);

                        if (StringUtils.equals(spTitle, title)) {
                            isOnePlay = false;
                            lryAnimeSelectionAdapter.setIndex(i);
                            lryAnimeSelectionAdapter.notifyDataSetChanged();
                            binding.rvLryselection.scrollToPosition(i);
                            play(url);

                            return;
                        }
                    }

                    if (isOnePlay) {
                        url = response.body().getData().getLRYChapterList().get(0).getLRYChapterPath();
                        response.body().getData().getLRYChapterList().get(0).getTitle();
                        play(url);

                    }


                    binding.tvTitle.setText(response.body().getData().getTitle());
                } else {
                    ToastUtils.showLong("未找到相关数据");
                }


            }

            @Override
            public void onFailure(Call<AnimeLRYChapterModel> call, Throwable t) {
                LogUtils.d("网络请求失败:" + t.getMessage());
                ToastUtils.showLong("网络请求失败:" + t.getMessage());

            }
        });
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (url != null) {
            SPStaticUtils.put(url, binding.superVodPlayerView.getProgress());
        }


        binding.superVodPlayerView.onPause();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (url != null) {
            SPStaticUtils.put(url, binding.superVodPlayerView.getProgress());
        }

        binding.superVodPlayerView.onResume();


    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        networkIndex = 0;

        stopDisposable(yhdisposable);
        stopDisposable(disposable);
        if (title != null) {
            LogUtils.d("当前播放器进度A" + binding.superVodPlayerView.getProgress() + "-->" + title);
            SPStaticUtils.put(url + title, title);
        }

        if (url != null) {
            SPStaticUtils.put(url, binding.superVodPlayerView.getProgress());
        }


        binding.superVodPlayerView.resetPlayer();


    }

}
